import java.sql.*;
import java.util.Scanner;

public class Hello {
    //psvm
    public static void main(String[] args) {
        //jdbc 步骤
        // 1.加载驱动
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            //2.创建链接
            String url = "jdbc:mysql://localhost:3306/test";
            Connection connection = DriverManager.getConnection(url, "root", "");
            if (connection != null) {
                System.out.println("成功");
            }
            // 3.写sql
            String sql = "select * from user3";
            // 4.预编译sql
            PreparedStatement preparedStatement = connection.prepareStatement(sql);

            //5.执行sql
            ResultSet resultSet = preparedStatement.executeQuery(sql);
            //6.遍历结果
            while(resultSet.next())
            {
                int id = resultSet.getInt(1);
                String name = resultSet.getString(2);
                String pass = resultSet.getString(3);
                System.out.println(id + " " + name + " " + pass);
            }
            //7.关闭资源（谁最后创建的谁最先关闭）
            resultSet.close();
            preparedStatement.close();
            connection.close();


        } catch (ClassNotFoundException | SQLException e) {
            throw new RuntimeException(e);
        } finally {
            //关闭资源的代码放在这第七步里更合理，但若放在这里，需扩大try的范围。
        }

    }

}
